/* eslint-disable camelcase */
// 封装axios
import store from '@/store'
import { Toast } from 'antd-mobile'
import axios, { AxiosError } from 'axios'
import history from '@/utils/history'
import { getToken, setToken } from './storage'
// const baseURL = 'http://geek.itheima.net/v1_0/'
const baseURL = 'http://toutiao.itheima.net/v1_0'
const instance = axios.create({
  baseURL,
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    // 如果有token就带上
    const token = getToken().token
    if (token) {
      config.headers!.Authorization = `Bearer ${token}`
      // config.headers?.Authorization = `Bearer ${token}` // 错误
      // if (config.headers) {
      //   config.headers.Authorization = `Bearer ${token}`
      // }
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response
  },
  async function (error) {
    const err = error as AxiosError
    // 对响应错误做点什么
    console.dir(err)
    if (!err.response) {
      Toast.show({ icon: 'fail', content: '网络异常' })
      return Promise.reject(error)
    }
    if (err.response?.status === 401) {
      // 处理401
      // eslint-disable-next-line no-unused-vars
      const { refresh_token } = getToken()
      if (!refresh_token) {
        // 去登录
        // 页面跳转
        history.push({
          pathname: '/login',
          state: { from: history.location.pathname }
        })
        return Promise.reject(error)
      }
      try {
        // 取新token
        const res = await axios.put(baseURL + 'authorizations', null, {
          headers: {
            Authorization: `Bearer ${refresh_token}`
          }
        })
        const newTokenInfo = { token: res.data.data.token, refresh_token }
        // 保存新token
        setToken(newTokenInfo)
        // redux
        store.dispatch({
          type: 'login/token',
          payload: newTokenInfo
        })

        // 重发请求
        return instance(err.config)
      } catch (err) {
        history.push({
          pathname: '/login',
          state: { from: history.location.pathname }
        })
        return Promise.reject(error)
      }
    }

    return Promise.reject(error)
  }
)

export default instance
